from web.webbase import *
from get import getclass,getpositions,getassets

def accounts():
    items={}
    getclass(items,'account',None,None,None,None)
    return items.values()

def accounttotals(acctids,dtstart,dtend):
    # collect information on positions
    positions={}
    getpositions(positions,acctids,dtstart,dtend)
    # add information on assets
    assets={}
    uniqueids=set(o['UNIQUEID'][0] for o in positions.itervalues()) # get all uniqueids in use
    getassets(assets,uniqueids)
            
    # collect information on accounts
    accounts={}
    # get general information on accounts which is NOT time dependent
    getclass(accounts,'account',acctids,None,None,None)
    # collect information on statements
    getclass(accounts,'accountdtasof',acctids,dtstart,dtend,None)
    # for each account and DTASOF, sum up MKTVAL of all positions.
    for o in positions.itervalues():
        if o['type']!='position': continue
        if 'MKTVAL' not in o: continue
        row={'ACCTID':o['ACCTID'],
             'DTASOF':o['DTASOF'],
             'mktval':o['MKTVAL']}
        # count monetmarket that are marked as CASH
        if 'CASH' in assets.get(o['UNIQUEID'][0],{}).get('assetClass',[]):
            row['moneymrkt']=o['MKTVAL']
        row2class(accounts,row,"accountdtasof")
    # Add cash to total value
    for o in accounts.itervalues():
        if o['type']!='accountdtasof': continue
        if 'AVAILCASH' not in o:
            o['AVAILCASH']=o.get('moneymrkt',[0.])
        if 'mktval' in o:            
            o['mktval'][0]+=o['AVAILCASH'][0]-o.get('moneymrkt',[0.])[0]
        else:
            o['mktval']=o['AVAILCASH']
        o['mktval'][0]+=o.get('BALAMT',[0.])[0]
        
    accountdtasofs = [o for o in accounts.itervalues()
                      if o['type']=='accountdtasof']
    for o in accountdtasofs:
        ACCTID=o['ACCTID'][0]
        accountGroups=accounts[ACCTID].get('accountGroup',[])
        for accountGroup in accountGroups:
            row2class(accounts,{'accountGroup':[accountGroup],
                            'dayasof':[o['DTASOF'][0][:10]],
                            'mKTVAL':o['mktval']},'groupdayasof')
    
    return accounts.values()
